const crypto = require('crypto');
export default {
	// 生成邀请码
	generateInviteCode(uid) {
		let chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
		let result = [];
		uid = uid.replace(/-/g, '');
		for (let i = 0; i < 8; i++) {
			let str = uid.slice(i * 3, i * 3 + 3);
			let num = parseInt(str, 16);
			result.push(chars[num % 62]);
		}
		return result.join('');
	},
	uuid(len, radix) {
		var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
		var uuid = [],
			i;
		radix = radix || chars.length;
		if (len) {
			// Compact form
			for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
		} else {
			// rfc4122, version 4 form
			var r;
			// rfc4122 requires these characters
			uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
			uuid[14] = '4';
			// Fill in random data.  At i==19 set the high bits of clock sequence as
			// per rfc4122, sec. 4.1.5
			for (i = 0; i < 36; i++) {
				if (!uuid[i]) {
					r = 0 | (Math.random() * 16);
					uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
				}
			}
		}
		return uuid.join('');
	},
	/**
	 * 随机数
	 * @param {Object} min
	 * @param {Object} max
	 */
	random(min, max) {
		if (min >= 0 && max > 0 && max >= min) {
			return Math.floor(Math.random() * (max - min)) + min;
		} else {
			return 0;
		}
	},
	/**
	 * 验证url
	 * @param {Object} value
	 */
	isUrl(value) {
		return /^((https|http|ftp|rtsp|mms):\/\/)(([0-9a-zA-Z_!~*'().&=+$%-]+: )?[0-9a-zA-Z_!~*'().&=+$%-]+@)?(([0-9]{1,3}.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z].[a-zA-Z]{2,6})(:[0-9]{1,4})?((\/?)|(\/[0-9a-zA-Z_!~*'().;?:@&=+$,%#-]+)+\/?)$/.test(
			value
		);
	},
	/**
	 * 验证邮箱
	 * @param {Object} value
	 */
	isEmail(value) {
		return /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
			value
		);
	},
	/**
	 * 中文
	 */
	isChinese(value) {
		let reg = /^[\u4e00-\u9fa5]+$/gi;
		return reg.test(value);
	},
	/**
	 * 只能输入字母
	 */
	isLetter(value) {
		return /^[a-zA-Z]*$/.test(value);
	},
	/**
	 * 只能是字母或者数字
	 */
	enOrNum(value) {
		//英文或者数字
		let reg = /^[0-9a-zA-Z]*$/g;
		return reg.test(value);
	},
	/**
	 * 验证手机号码
	 * @param {Object} value
	 */
	isMobile(value) {
		return /^(?:(?:\+|00)86)?1\d{10}$/.test(value);
	},
	/**
	 * 是否是固定电话
	 * @param {Object} value
	 */
	isPhone(value) {
		let reg = /^\d{3}-\d{8}$|^\d{4}-\d{7,8}$/;
		return reg.test(value);
	},
	/**
	 * 深度复制
	 * @param {Object} parent
	 * @param {Object} child
	 */
	deepClone(parent, child) {
		var i, proxy;
		proxy = JSON.stringify(parent); //把parent对象转换成字符串
		proxy = JSON.parse(proxy); //把字符串转换成对象，这是parent的一个副本
		child = child || {};
		for (i in proxy) {
			//排除原型链
			if (proxy.hasOwnProperty(i)) {
				child[i] = proxy[i];
			}
		}
		proxy = null; //因为proxy是中间对象，可以将它回收掉
		return child;
	},
	/**
	 * 字符串命名风格转换
	 */
	caseTransform(str, type = -1) {
		let str1 = '',
			str2 = '',
			str3 = '',
			array = [];
		if (str.includes('-')) {
			str3 = str.replace(/-/g, '_');
			let arr = str.split('-');
			arr.forEach((item) => {
				str1 += item.slice(0, 1).toUpperCase() + item.slice(1);
			});
			str2 = str1.slice(0, 1).toLowerCase() + str1.slice(1);
			array = [str1, str2, str3, str];
		} else if (str.includes('_')) {
			str3 = str.replace(/_/g, '-');
			let arr = str.split('_');
			arr.forEach((item) => {
				str1 += item.slice(0, 1).toUpperCase() + item.slice(1);
			});
			str2 = str1.slice(0, 1).toLowerCase() + str1.slice(1);
			array = [str1, str2, str, str3];
		} else if (/[A-Z]/.test(str.slice(0, 1))) {
			str1 = str.slice(0, 1).toLowerCase() + str.slice(1);
			let arr = str1.split('');
			arr.forEach((item) => {
				if (/[A-Z]/.test(item)) {
					item = item.toLowerCase();
					str2 += '_';
					str3 += '-';
				}
				str2 += item;
				str3 += item;
			});
			array = [str, str1, str2, str3];
		} else {
			let arr = str.split('');
			arr.forEach((item) => {
				if (/[A-Z]/.test(item)) {
					item = item.toLowerCase();
					str2 += '_';
					str3 += '-';
				}
				str2 += item;
				str3 += item;
			});
			str1 = str.slice(0, 1).toUpperCase() + str.slice(1);
			array = [str1, str, str2, str3];
		}
		if (type < 0 || type > 3) return array;
		return array[type];
	},
	/**
	 * 验证十进制数字
	 * 此判断函数源于uview前端框架。
	 * @param {Object} value
	 */
	isNumeric(value) {
		return /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value);
	},
	/**
	 * 是否是json string
	 * 此判断函数源于uview前端框架。
	 * @param {Object} value
	 */
	jsonString(value) {
		if (typeof value == 'string') {
			try {
				var obj = JSON.parse(value);
				if (typeof obj == 'object' && obj) {
					return true;
				} else {
					return false;
				}
			} catch (e) {
				return false;
			}
		}
		return false;
	},
	/**
	 * 是否数组
	 * 此判断函数源于uview前端框架。
	 */
	isArray(value) {
		if (typeof Array.isArray === 'function') {
			return Array.isArray(value);
		} else {
			return Object.prototype.toString.call(value) === '[object Array]';
		}
	},
	/**
	 * 是否对象
	 * 此判断函数源于uview前端框架。
	 */
	isObject(value) {
		return Object.prototype.toString.call(value) === '[object Object]';
	},
	/**
	 * 判断是否为空
	 * 此判断函数源于uview前端框架。
	 */
	isEmpty(value) {
		switch (typeof value) {
			case 'undefined':
				return true;
			case 'string':
				if (value.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length == 0) return true;
				break;
			case 'boolean':
				if (!value) return true;
				break;
			case 'number':
				if (0 === value || isNaN(value)) return true;
				break;
			case 'object':
				if (null === value || value.length === 0) return true;
				for (var i in value) {
					return false;
				}
				return true;
		}
		return false;
	},
	/**
	 * 密码加密解密
	 * @param {Object} type
	 * @param {Object} passwordSecret
	 */
	getPasswordExtMethod(type, passwordSecret) {
		switch (type) {
			case 'hmac-sha1':
				return {
					verify(password, originPasswordHash, passwordSecretVersion) {
						if (passwordSecretVersion !== passwordSecret.version) {
							return false;
						}
						const { passwordHash } = this.encrypt(password);
						return passwordHash === originPasswordHash;
					},
					encrypt(password) {
						const { type, version } = passwordSecret;
						const hmac = crypto.createHmac('sha1', type.toString('ascii'));
						hmac.update(password);
						return {
							passwordHash: hmac.digest('hex'),
							version,
						};
					},
				};
			case 'hmac-sha256':
				return {
					verify(password, originPasswordHash, passwordSecretVersion) {
						if (passwordSecretVersion !== passwordSecret.version) {
							return false;
						}
						const algorithm = 'UNI_ID_HMAC_SHA256';
						let [, , len, saltPassword] = originPasswordHash.split('$');
						len = Number(len);
						if (!len || !saltPassword || isNaN(len)) {
							return false;
						}
						let salt = saltPassword.slice(0, len);
						const sha256Hash = crypto.createHmac('sha256', salt).update(password).digest('hex');
						return `$${algorithm}$${salt.length}$${salt}${sha256Hash}` === originPasswordHash;
					},
					encrypt(password) {
						const { version } = passwordSecret;
						// 默认使用 sha256 加密算法
						const salt = crypto.randomBytes(10).toString('hex');
						const sha256Hash = crypto.createHmac('sha256', salt).update(password).digest('hex');
						const algorithm = 'UNI_ID_HMAC_SHA256';
						// B 为固定值，对应 PasswordMethodMaps 中的 sha256算法
						// hash 格式 $[PasswordMethodFlagMapsKey]$[salt size]$[salt][Hash]
						const passwordHash = `$${algorithm}$${salt.length}$${salt}${sha256Hash}`;
						return {
							passwordHash,
							version,
						};
					},
				};
		}
	},
};
